package com.yykj.common.aspect;

import com.yykj.common.annotation.FrequencyLimit;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.service.RedisService;
import com.yykj.common.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by chendg
 * on 2019/6/28 0028.
 */

@Aspect
@Slf4j
@Component

public class FrequencyLimitAspect {

    @Pointcut("@annotation(com.yykj.common.annotation.FrequencyLimit))")
    public void verify() {
    }

    /**
     * 检查token
     *
     * @param joinPoint 切入点
     */
    @Before("verify()")
    public void doVerify(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        StringBuilder sb = new StringBuilder();
        for (Object obj : args) {
            sb.append(obj.toString());
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        FrequencyLimit annotation = method.getAnnotation(FrequencyLimit.class);

        sb.append(method.toString());
        String key = MD5Util.md5Encode(sb.toString());

        long value = System.currentTimeMillis() + annotation.value();
        if (!redisService.lock(key, String.valueOf(value))) {
            throw new NormalException(ResultEnums.SYSTEM_FREQUENCY_LIMIT_ERROR);
        } else {
            log.info("【FrequencyLimitAspect】 ,key = {}", key);
            redisService.expire(key, 5);
        }

    }

    private RedisService redisService;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }
}
